<?php

namespace App\Http\Controllers;

use App\Services\OSS;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Database\Eloquent\Model;
class WxController extends Controller
{
    use \App\Traits\ApiTrait, \App\Traits\SessionTrait, \App\Traits\AjaxTrait, \App\Traits\DbTrait, \App\Traits\UserTrait;
    public $templatePushUrl = 'https://api.weixin.qq.com/cgi-bin/message/template/send';
    public $createMenuUrl = 'https://api.weixin.qq.com/cgi-bin/menu/create';
    public $webTokenUrl = 'https://api.weixin.qq.com/sns/oauth2/access_token';
    public $accessTokenUrl = 'https://api.weixin.qq.com/cgi-bin/token';
    public $clientGrantType = 'client_credential';
    public $webGrantType = 'authorization_code';
    public $curl;
    public function __construct() {
		$this->curl = new \Ixudra\Curl\CurlService();
	}
    public $AkInfo= [
                    	'default_app_id' => 'wxef0f4b8d99aa8de5',
                    	'appInfo' => [
                    		'wxef0f4b8d99aa8de5' => [
                    			'app_id' => 'wxef0f4b8d99aa8de5',
                    			'secret' => '44fe3c475e9bfdb744e2e07c88e87956',
                    			'token' => 'waken',
                    		],
                    		'wx6465750988a2f203' => [
                    			'app_id' => 'wx6465750988a2f203',
                    			'secret' => '1cfdebb6d7e9db07f3d7a5be645717a6',
                    			'token' => 'waken',
                    		],
                    	],
                    ];
    public $token='waken';
/* 是否已经绑定的用户
*/
    public function _isUser(){
      $accessToken=$this->getAccessToken();
      $openid = $_REQUEST['openid'];
      // $openid='dsfafafaf';
      // $appkey = $request->input('appkey');
      $requestUrl='http://114.215.198.115:23831/ctm/v1/isExistOppenId';
      $result=$this->curl->to($requestUrl)
      ->withOption('TIMEOUT', 10)
      ->withData(['oppenid'=>$openid,'device'=>'weixin'])
      ->post();
      $result=json_decode($result,true);
      if($result['data'] && $result['data']['isexist']==1)
      return 1;
      return 0;
    }

    public function wxLogin(){
        $openid = $_REQUEST['openid'];
        $isUser=$this->_isUser();
        if($isUser==1){

        }
        else {
          $viewData=['openid'=>$openid];
          return view('wx/login',$viewData);
        }
    }

    public function verifyLogin(){
      $openid = $_REQUEST['openid'];
      $userName=$_REQUEST['userName'];
      $cellphone=$_REQUEST['cellphone'];
      $requestData=['openid'=>$openid,'personal_name'=>$userName,'personal_mobile'=>$cellphone];
      $result = $this->curl->to("114.215.198.115:23831/ctm/v1/addWPersonal")
      ->withOption('TIMEOUT', 10)
      ->withData($requestData)
      ->post();
      var_dump($result);
    }

    public function createMenu(){

    }

    public function getAccessToken(){
      $tokenLast= DB::table('WX_AccessKey')->first();
      $nowTime=time();
      $nowTime=$nowTime-7200;
      //Access_token是否过期
      if($nowTime<$tokenLast->expireTime){
        $AK=$tokenLast->AK;
        // var_dump($AK);
      }
      else{
        $secret=$this->AkInfo['appInfo']['wxef0f4b8d99aa8de5']['secret'];
        $requestData=['grant_type'=>$this->clientGrantType,'appid'=>$this->AkInfo['default_app_id'],'secret'=>$secret];
        $result = $this->curl->to($this->accessTokenUrl)
  			->withOption('TIMEOUT', 10)
  			->withData($requestData)
  			->get();
        $result=json_decode($result,true);
        $AK=$result['access_token'];
        $time=time()+7200;
        DB::insert("insert into WX_AccessKey (AK,expireTime) values ('$AK','$time')");
      }
      // echo $AK;
      return $AK;
    }

    private function _checkSignature($request)
    {
        $signature = $request->input('signature');
        $timestamp = $request->input('timestamp');
        $nonce = $request->input('nonce');
        $token = $this->token;

        $tmpArr = array($token, $timestamp, $nonce);
        sort($tmpArr, SORT_STRING);
        $tmpStr = implode($tmpArr);
        $tmpStr = sha1($tmpStr);

        return ($tmpStr == $signature) ? true : false;
    }
}
